package service

import (
	"context"
	"database/sql"
	"fx_swift_ifcgate_agent/api"
	"fx_swift_ifcgate_agent/internal/model"
	"fx_swift_ifcgate_agent/pkg/code"
	"fx_swift_ifcgate_agent/pkg/global"
	"fx_swift_ifcgate_agent/pkg/internalerrors"
	"fx_swift_ifcgate_agent/pkg/logger"
	"fx_swift_ifcgate_agent/pkg/page"
	"fx_swift_ifcgate_agent/pkg/utils"
	"github.com/spf13/cast"
)

type IInvitationSrv interface {
	CreateInvitationCode(ctx context.Context, req *api.InvitationCodeReq) (string, error)
	ViewInvitationStatistics(ctx context.Context, invitId string) ([]*api.InvitationStatisticsRes, error)
	QueryInvitationList(ctx context.Context, req *api.InvitationListReq) (*page.Collection[*api.InvitationCodeRes], error)
}

type invitationSrv struct {
}

func NewInvitationSrv() IInvitationSrv {
	return &invitationSrv{}
}

// 邀请码列表
func (i invitationSrv) QueryInvitationList(ctx context.Context, req *api.InvitationListReq) (*page.Collection[*api.InvitationCodeRes], error) {
	var (
		err               error
		invitationCodeObj []*api.InvitationCodeRes
		total             int
	)
	collectionDto := &page.Collection[*api.InvitationCodeRes]{}
	collectionDto.Page = req.PageNo
	collectionDto.PageSize = req.PageSize

	agentAccount := ctx.Value("Account").(string)
	mod := global.GFDB.Model("ifcgate_invitation_code")
	mod.Where("agent_account", agentAccount)
	mod.Order("created_at desc")
	mod.Limit(int(page.PageToOffset(req.PageNo, req.PageSize)), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&invitationCodeObj, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(req.PageNo, req.PageSize, cast.ToInt64(total))

	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}

	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = invitationCodeObj

	return collectionDto, nil
}

// 查看邀请成功记录
func (i invitationSrv) ViewInvitationStatistics(ctx context.Context, invitId string) ([]*api.InvitationStatisticsRes, error) {
	var (
		err                error
		invitStatisitcsObj []*api.InvitationStatisticsRes
	)
	sqlStr := "select DATE_FORMAT(created_at,'%Y-%m') as `date`,count(1) as nums from fx.ifcgate_company_user where invit_id=? group by DATE_FORMAT(created_at,'%Y-%m') order by DATE_FORMAT(created_at,'%Y-%m') desc"
	err = global.GFDB.Raw(sqlStr, invitId).Scan(&invitStatisitcsObj)
	if err != nil {
		return []*api.InvitationStatisticsRes{}, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if invitStatisitcsObj == nil {
		return []*api.InvitationStatisticsRes{}, nil
	}

	return invitStatisitcsObj, nil
}

// 新增邀请码
func (i invitationSrv) CreateInvitationCode(ctx context.Context, req *api.InvitationCodeReq) (string, error) {
	var (
		err            error
		agentAccount   string
		invitationCode string
		result         sql.Result
		rowsNums       int64
	)

	agentAccount = ctx.Value("Account").(string)
	invitationCode = utils.GenerateInviteCode(agentAccount)
	//入库
	if result, err = global.GFDB.Insert(ctx, "ifcgate_invitation_code", &model.IfcgateInvitationCode{
		AgentAccount:   agentAccount,
		InvitationCode: invitationCode,
		Remark:         req.Remark,
	}); err != nil {
		logger.SugarLogger.Error(err)
		return "", internalerrors.New(code.ErrUnknown, "新增失败")
	}
	rowsNums, err = result.RowsAffected()
	if rowsNums == 0 {
		return "", internalerrors.New(code.ErrUnknown, "新增失败")
	}
	return invitationCode, nil
}
